package com.finance.capacity.siteSummary.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.capacity.common.capService.ICapOrganizationService;
import com.finance.capacity.siteMonth.bean.pojo.SiteMonthDetail;
import com.finance.capacity.siteMonth.bean.pojo.SiteMonthList;
import com.finance.capacity.siteMonth.bean.pojo.SiteMonthPageList;
import com.finance.capacity.siteMonth.capService.ISiteMonthService;
import com.finance.capacity.siteSummary.request.SiteMonthListReq;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: gly
 * @Date: Created in 2017-09-18
 */
@Controller
@RequestMapping("/capacity/summary")
public class SiteSummaryController extends BaseController {
    @Resource
    private ISiteMonthService siteMonthService;
    @Resource
    private ICapOrganizationService capOrganizationService;

    /**
     * 站点运力月度汇总展示
     *
     * @param form
     * @return
     */
    @RequestMapping("/listall")
    public Result list(SiteMonthListReq form) {
        Page page = Page.getInstance(form);
        SiteMonthList siteMonthList = new SiteMonthList();
        siteMonthList.setProvinceId(form.getProvinceId());
        siteMonthList.setCityId(form.getCityId());
        siteMonthList.setSiteId(form.getSiteId());
        if (StringUtils.isNotBlank(form.getKeyWords())) {
            List<String> keyWordsList = new ArrayList<String>();
            List<String> names = Arrays.asList(form.getKeyWords().split("、"));
            for (String orgName : names) {
                List<String> orgCodes = capOrganizationService.getIdByName(orgName);
                if(orgCodes!=null&&orgCodes.size()>0) {
                    keyWordsList.addAll(orgCodes);
                }else {
                   orgCodes.add("no_site");
                   keyWordsList.addAll(orgCodes);
                }
            }
            siteMonthList.setKeyWords(keyWordsList);
        }
        page.setParams(siteMonthList);
        PageResultBO<SiteMonthPageList> resultBO = siteMonthService.siteSummaryListByPage(page);
        List<SiteMonthPageList> dataList = resultBO.getDataList();
        fillSiteList(dataList, form);
        return getSuccessResult(resultBO);
    }

    /**
     * 站点运力月度汇总导出
     *
     * @param form
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/export")
    public Result export(SiteMonthListReq form, HttpServletResponse response) throws UnsupportedEncodingException {
        SiteMonthList siteMonthList = new SiteMonthList();
        siteMonthList.setProvinceId(form.getProvinceId());
        siteMonthList.setCityId(form.getCityId());
        siteMonthList.setSiteId(form.getSiteId());
        if (!StringUtils.isBlank(form.getKeyWords())) {
            List<String> keyWordsList = new ArrayList<String>();
            List<String> names = Arrays.asList(form.getKeyWords().split("、"));
            for (String orgName : names) {
                List<String> orgCodes = capOrganizationService.getIdByName(orgName);
                if(orgCodes!=null&&orgCodes.size()>0) {
                    keyWordsList.addAll(orgCodes);
                }else {
                    orgCodes.add("no_site");
                    keyWordsList.addAll(orgCodes);
                }
            }
            siteMonthList.setKeyWords(keyWordsList);

        }
        List<SiteMonthPageList> exportList = siteMonthService.siteSummaryExport(siteMonthList);
        fillSiteList(exportList, form);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "年度站点运力汇总" + sdf.format(new Date());
        String suffix = ".xls";
        fileName = fileName + suffix;
        // 声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet("年度站点运力汇总列表");
        sheet.createDrawingPatriarch();
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        //第一行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("组织架构");
        row.getCell(0).setCellStyle(cellStyle);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        if (StringUtils.isNotBlank(form.getSiteMonths())) {
            List<String> siteMonths = Arrays.asList(form.getSiteMonths().split("\\*"));
            if (siteMonths.size() == 1 && siteMonths.get(0).endsWith("X")) {
                String year = siteMonths.get(0).replace("-X", "");
                String[] titlesUnFixed = new String[]{year + "年01月", year + "年02月", year + "年03月", year + "年04月", year + "年05月", year + "年06月", year + "年07月", year + "年08月", year + "年09月", year + "年10月", year + "年11月", year + "年12月"};
                for (int i = 0; i < 12; i++) {
                    row.createCell(4 + 3 * i).setCellValue(titlesUnFixed[i]);
                    row.getCell(4 + 3 * i).setCellStyle(cellStyle);
                    sheet.addMergedRegion(new CellRangeAddress(0, 0, 4 + 3 * i, 6 + 3 * i));

                }
            } else {
                for (int i = 0; i < siteMonths.size(); i++) {
                    StringBuilder sb = new StringBuilder(siteMonths.get(i).replace("-", "年")).append("月");
                    row.createCell(4 + 3 * i).setCellValue(sb.toString());
                    row.getCell(4 + 3 * i).setCellStyle(cellStyle);
                    sheet.addMergedRegion(new CellRangeAddress(0, 0, 4 + 3 * i, 6 + 3 * i));


                }
            }
        }
        // 第二行
        row = sheet.createRow(1);
        String[] titlesFixed = new String[]{"序号", "省公司", "市公司", "站点"};
        List<String> titles = new ArrayList<String>();
        titles.addAll(Arrays.asList(titlesFixed));
        for (int i = 0; i < titles.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(titles.get(i));
        }
        if (StringUtils.isNotBlank(form.getSiteMonths())) {
            List<String> siteMonths = Arrays.asList(form.getSiteMonths().split("\\*"));
            if (siteMonths.size() == 1 && siteMonths.get(0).endsWith("X")) {
                for (int i = 0; i < 12; i++) {
                    row.createCell(3 * i + 4).setCellValue("总人效单量");
                    row.createCell(3 * i + 5).setCellValue("总出勤人数");
                    row.createCell(3 * i + 6).setCellValue("站点人效");
                }

            } else {
                for (int i = 0; i < siteMonths.size(); i++) {
                    row.createCell(3 * i + 4).setCellValue("总人效单量");
                    row.createCell(3 * i + 5).setCellValue("总出勤人数");
                    row.createCell(3 * i + 6).setCellValue("站点人效");
                }
            }
        }
        // 数据行
        if (exportList != null && exportList.size() > 0) {
            for (int i = 0; i < exportList.size(); i++) {
                SiteMonthPageList siteMonthExport = exportList.get(i);
                row = sheet.createRow(i + 2);
                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue(siteMonthExport.getProvinceName());
                row.createCell(2).setCellValue(siteMonthExport.getCityName());
                row.createCell(3).setCellValue(siteMonthExport.getSiteName());
                if (StringUtils.isNotBlank(form.getSiteMonths())) {
                    List<String> siteMonths = Arrays.asList(form.getSiteMonths().split("\\*"));
                    if (siteMonths.size() == 1 && siteMonths.get(0).endsWith("X")) {
                        for (int x = 0; x < 12; x++) {
                            row.createCell(3 * x + 4).setCellValue(0.00);
                            row.createCell(3 * x + 5).setCellValue(0);
                            row.createCell(3 * x + 6).setCellValue(0);
                        }
                        for (int x = 1; x < 13; x++) {
                            Iterator<SiteMonthDetail> iterator = siteMonthExport.getSiteList().iterator();
                            while (iterator.hasNext()) {
                                SiteMonthDetail siteMonthDetail = iterator.next();
                                if (x < 10) {
                                    if (siteMonthDetail.getSiteMonth().endsWith("0" + x)) {
                                        row.createCell(3 * (x - 1) + 4).setCellValue(siteMonthDetail.getOrderEfficientNum());
                                        row.createCell(3 * (x - 1) + 5).setCellValue(siteMonthDetail.getWorkerNum());
                                        row.createCell(3 * (x - 1) + 6).setCellValue(String.valueOf(siteMonthDetail.getSiteEfficiency()));
                                    }
                                } else {
                                    if (siteMonthDetail.getSiteMonth().endsWith(String.valueOf(x))) {
                                        row.createCell(3 * (x - 1) + 4).setCellValue(siteMonthDetail.getOrderEfficientNum());
                                        row.createCell(3 * (x - 1) + 5).setCellValue(siteMonthDetail.getWorkerNum());
                                        row.createCell(3 * (x - 1) + 6).setCellValue(String.valueOf(siteMonthDetail.getSiteEfficiency()));
                                    }
                                }

                            }


                        }
                    } else {
                        for (int x = 0; x < siteMonths.size(); x++) {
                            row.createCell(3 * x + 4).setCellValue(0.00);
                            row.createCell(3 * x + 5).setCellValue(0);
                            row.createCell(3 * x + 6).setCellValue(0);
                        }
                        for (int x = 0; x < siteMonths.size(); x++) {
                            Iterator<SiteMonthDetail> iterator = siteMonthExport.getSiteList().iterator();
                            while (iterator.hasNext()) {
                                SiteMonthDetail siteMonthDetail = iterator.next();
                                if (siteMonths.get(x).equals(siteMonthDetail.getSiteMonth())) {
                                    row.createCell(3 * x + 4).setCellValue(siteMonthDetail.getOrderEfficientNum());
                                    row.createCell(3 * x + 5).setCellValue(siteMonthDetail.getWorkerNum());
                                    row.createCell(3 * x + 6).setCellValue(String.valueOf(siteMonthDetail.getSiteEfficiency()));
                                }
                            }
                        }
                    }
                }
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream;
            try {
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return getFailResult(BaseConstants.ERR_UNKOWN, e.getMessage());
            }
            return getSuccessResult("导出成功");

        } else {
            return getFailResult(BaseConstants.ERR_RESULT_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_RESULT_NULL));
        }

    }

    private void fillSiteList(List<SiteMonthPageList> dataList, SiteMonthListReq form) {
        Iterator iterator = dataList.iterator();
        while (iterator.hasNext()) {
            SiteMonthList siteMonthList = new SiteMonthList();
            SiteMonthPageList siteMonthPageList = (SiteMonthPageList) iterator.next();
            String siteId = siteMonthPageList.getSiteId();
            if (StringUtils.isNotBlank(form.getSiteMonths())) {
                List<String> siteMonths = Arrays.asList(form.getSiteMonths().split("\\*"));
                if (siteMonths.size() == 1 && siteMonths.get(0).endsWith("X")) {
                    String monthAll = siteMonths.get(0).replace("X", "").trim();
                    siteMonthList.setMonthAll(monthAll);
                } else {
                    siteMonthList.setSiteMonths((siteMonths));
                }
            }
            siteMonthList.setSiteId(siteId);
            List<SiteMonthDetail> siteMonthDetails = siteMonthService.siteSummaryDetail(siteMonthList);
            siteMonthPageList.setSiteList(siteMonthDetails);
        }
    }
}